
import { Component } from "react"

class DemoA extends Component {
  constructor(props) {
    super(props);
    this.state = {
      todo: "",
      list: [],
    }
  }
  getTodo(e) {
    this.setState({
      todo: e.target.value
    })
  }
  confirm() {
    // console.log(this.state.todo);
    if (!this.state.todo.trim()) {
      alert("输入框必须要输入内容");
      return;
    }
    this.setState(state => ({
      list: [...state.list, { id: Date.now(), task: this.state.todo }]
    }))
    this.setState({
      todo: ""
    })
  }
  addByEnter(e) {
    if (e.keyCode == 13) {
      this.confirm();
    }
  }
  delTodo(id) {
    // 数据不可变
    this.setState(state => ({
      list:state.list.filter(item=>item.id !== id)
    }))
  }
  render() {
    let { todo, list } = this.state;
    return (
      <div>
        <div>
          {/* <input type="text" value={todo} onInput={e => this.getTodo(e)} /> */}

          {/* vue中等价于v-model */}
          <input
            type="text"
            value={todo}
            onChange={e => this.getTodo(e)}
            onKeyUp={e => this.addByEnter(e)}
          />
          <button onClick={e => this.confirm(e)}>添加</button>
        </div>
        <div>
          {
            list.map((item, index, arr) => (
              <div key={item.id}>
                <span>{item.id}</span> -- <span>{item.task}</span>
                <button onClick={e=>this.delTodo(item.id)}>删除</button>
              </div>
            ))
          }
        </div>
      </div>
    )
  }
}

export default DemoA;